/*
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.blockly.ohos.ui.mutator;

import com.google.blockly.model.Mutator;
import com.google.blockly.model.mutator.IfElseMutator;
import com.google.blockly.ohos.ResourceTable;
import com.google.blockly.ohos.ui.MutatorFraction;
import ohos.agp.components.*;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.global.resource.NotExistException;

import java.io.IOException;

/**
 * Standard fraction UI for editing an if-else block. This fraction does not support restoring
 * across ability restarts and should not be included in the back stack.
 */
public class IfElseMutatorFraction extends MutatorFraction {
    public static final Factory FACTORY =
            new Factory<IfElseMutatorFraction>() {
                @Override
                public IfElseMutatorFraction newMutatorFraction(Context context, Mutator mutator) {
                    IfElseMutatorFraction fraction = new IfElseMutatorFraction(context);
                    fraction.init((IfElseMutator) mutator);
                    return fraction;
                }
            };

    private IfElseMutator mMutator;
    private String mElseIfCountString;
    private int mElseIfCount;
    private boolean mHasElse;

    private Image mRemoveElseIfButton;
    private Text mElseIfCountView;
    private Context mContext;
    private CommonDialog dialog;

    public IfElseMutatorFraction(Context context) {
        super(context);
        this.mContext = context;
    }

    /**
     * This must be called after the fraction is created with the mutator that it should show UI
     * for. Because of this extra initialization this fraction should not be restored across
     * ability recreations and should not be added to the back stack.
     *
     * @param mutator The mutator to show UI for.
     */
    public void init(IfElseMutator mutator) {
        mMutator = mutator;
        mElseIfCount = mutator.getElseIfCount();
        mHasElse = mutator.hasElse();
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        mElseIfCountString = mContext.getString(ResourceTable.String_mutator_ifelse_edit_ifelse_count);
        try {
            onCreateDialog();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
    }


    private void onCreateDialog() throws IOException, NotExistException {
        LayoutScatter helium = LayoutScatter.getInstance(mContext);
        Component contentView = helium.parse(ResourceTable.Layout_if_else_mutator_dialog, null, false);

        mElseIfCountView = (Text) contentView.findComponentById(ResourceTable.Id_if_else_count);
        updateCountString();

        mRemoveElseIfButton = (Image) contentView.findComponentById(ResourceTable.Id_remove_else_if);
        mRemoveElseIfButton.setClickedListener(component -> {
            mElseIfCount--;
            if (mElseIfCount <= 0) {
                mElseIfCount = 0;
                mRemoveElseIfButton.setEnabled(false);
            }
            updateCountString();
        });

        if (mElseIfCount == 0) {
            mRemoveElseIfButton.setEnabled(false);
        }

        Image iv = (Image) contentView.findComponentById(ResourceTable.Id_add_else_if);
        iv.setClickedListener(component -> {
            mElseIfCount++;
            if (!mRemoveElseIfButton.isEnabled()) {
                mRemoveElseIfButton.setEnabled(true);
            }
            updateCountString();
        });

        Checkbox elseCheckBox = (Checkbox) contentView.findComponentById(ResourceTable.Id_else_checkbox);
        elseCheckBox.setChecked(mHasElse);
        elseCheckBox.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(AbsButton absButton, boolean isChecked) {
                mHasElse = isChecked;
            }
        });

        Text done = (Text) contentView.findComponentById(ResourceTable.Id_done);
        done.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                finishMutation();
            }
        });

        int windowHeight = AttrHelper.vp2px(mContext.getResourceManager().getDeviceCapability().height, mContext);
        int windowWidth = AttrHelper.vp2px(mContext.getResourceManager().getDeviceCapability().width, mContext);
        this.setSize((int) (windowWidth * 0.9), (int) (windowHeight * 0.3));

        this.setContentCustomComponent(contentView);
    }

    private void updateCountString() {
        // Because the user always sees at least one "if", start the count at one.
        String elseIfCount = String.format(mElseIfCountString, mElseIfCount + 1);
        mElseIfCountView.setText(elseIfCount);
    }

    private void finishMutation() {
        mMutator.mutate(mElseIfCount, mHasElse);
        this.destroy();
    }
}
